const util = require("../../../utils/util.js");
const db = wx.cloud.database();
const _ = db.command
Page({
  data: {
    files: [],
    uploadImgArry: [],
    diy_name: '',
    uploadImgCount: 0,
    diy_id: '',
    newImgCount: 0,
    radio: '1',
    all: []
  },
  onLoad: function (options) {

    if (options.id == null || options.id == '') {
    } else {
      this.data.diy_id = options.id;  //说明是编辑
      db.collection('index_diy').where({
        _id: _.eq(options.id)
      }).get().then(res => {
        console.log("11111")
        console.log(res.data[0].files)
        //TODO
        this.setData({
          id: options.id,
          diy_name: res.data[0].name,
          files: res.data[0].files,
          radio: res.data[0].product
        })
      })
    }

  },
  chooseImage: function (e) {
    var that = this;
    var images = that.data.files;
    if (images.length > 0) {
      wx.showToast({
        icon: 'none',
        title: '只允许上传一张照片，请删除已有图片再上传',
      })
      return;
    }
    wx.chooseImage({
      count: 1 - images.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  deleteImage: function (e) {
    var that = this;
    var images = that.data.files;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '系统提醒',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          images.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }
        that.setData({
          files: images
        });
      }
    })
  },
  uploadImg: function (e) {
    console.log("123123");
    const filePath = e
    // 上传图片
    const cloudPath = "templateimg/" + (new Date()).valueOf() + filePath.match(/\.[^.]+?$/)[0]
    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: res => {
        console.log('[上传文件] 成功：', res)
        console.log(this.data.uploadImgArry);
        this.setData({
          uploadImgArry: this.data.uploadImgArry.concat(res.fileID)
        })

        console.log(this.data.uploadImgArry);
        this.setData({
          uploadImgCount: this.data.uploadImgCount + 1
        })

        console.log(this.data.uploadImgCount);
        console.log(this.data.files.length)
        if (this.data.newImgCount == this.data.uploadImgCount) {
          // this.setData({
          //   uploadImgArry: this.data.uploadImgArry.concat(res.fileID)
          // })
          this.submitCloudData()
        }
      },
      fail: e => {
        console.error('[上传文件] 失败：', e)
        wx.showToast({
          icon: 'none',
          title: '上传失败',
        })
        wx.hideLoading();
      },
      complete: () => {
      }
    })

  },
  submitCloudData(e) {
    console.log(this.data.proGg)



    if (this.data.diy_id != '') {  //判断数据库是否已存在过编辑记录
      db.collection('index_diy').doc(this.data.diy_id).update({
        // data 传入需要局部更新的数据
        data: {
          createtime: util.formatTime(new Date()),
          name: this.data.diy_name,
          product: this.data.radio,
          files: this.data.uploadImgArry
        },
        success(res) {
          // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
          console.log(res)
          wx.showToast({
            title: '发布成功',
          });
          setTimeout(function () {
            wx.hideLoading()
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2];
            prevPage.setData({
              req: 1
            })
            wx.navigateBack()
          }, 1000)
        },
        fail: console.error
      })
    } else {
      let d = {
        name: "首页",
        content: []
      }
      let a = this.data.all
      a.push(d)
      if (this.data.radio == 1) {
        let splb = {
          name: "商品列表",
          content: [],
          url: "../../../pages/shop/product/product-list/index"
        }
        a.push(splb)
      }

      this.setData({
        all: a
      })
      db.collection('index_diy').add({
        // data 字段表示需新增的 JSON 数据
        data: {
          type: "template",
          createtime: util.formatTime(new Date()),
          all: this.data.all,
          name: this.data.diy_name,
          product: this.data.radio,
          files: this.data.uploadImgArry
        }
      })
        .then(res => {
          console.log(res)
          wx.showToast({
            title: '发布成功',
          })
          setTimeout(function () {
            wx.hideLoading()
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2];
            prevPage.setData({
              req: 1
            })
            wx.navigateBack()
          }, 1000)
        })
    }
  },

  onClickSave() {
    if (this.data.diy_name == null || this.data.diy_name == '') {
      wx.showToast({
        title: '模板名称不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    wx.showLoading({
      title: '数据同步中',
    })
    console.log(this.data.files)
    for (var i = 0; i < this.data.files.length; i++) {
      if (this.data.files[i].indexOf("http://")==0) {
        console.log("222");
        this.setData({
          newImgCount: this.data.newImgCount + 1
        })

      } else {
        console.log("3333");
        this.setData({
          uploadImgArry: this.data.uploadImgArry.concat(this.data.files[i])
        })
      }
    }
    for (var i = 0; i < this.data.files.length; i++) {
      if (this.data.files[i].indexOf("http://")==0){
        this.uploadImg(this.data.files[i]);
      }
        
    }
    if (this.data.files.length == 0 || this.data.files.length == this.data.uploadImgArry.length) {
      this.submitCloudData()
    }
  },
  getProName: function (e) {
    this.setData({
      diy_name: e.detail
    })
  },
  onRadioClick: function (e) {
    this.setData({
      radio: e.currentTarget.dataset.name
    })

  },
  onRdaioChange: function (e) {
    console.log(e)

  }
});